/*
 * Copyright 2012-2013 EZC Group S.A. RCS Luxembourg B140949
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.yobidrive.y3.v1;

import java.io.InputStream;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.yobidrive.y3.client.Y3Client;

public class Y3ClientFactory {
	static private final Logger logger = Logger.getLogger(Y3ClientFactory.class);
	static private final String PROPERTIES_FILE_NAME = "YobiFSProxy.cfg.xml";
	static private final String IMPLEMENTATION_CLASS = "y3clientclass";
	
	static private boolean initializationDone = false;
	static private Properties properties = null;
	
	public static Y3 buildClient() {
		if ( !initializationDone )
			initializeFactory();
		
		if ( properties == null) {
			logger.fatal("Could not determine implementation class because configuration file is not loaded");
			return null;
		}
		
		String implementationClass = properties.getProperty(IMPLEMENTATION_CLASS);
		if ( implementationClass == null || "".equals(implementationClass)) {
			logger.fatal("Property "+IMPLEMENTATION_CLASS+" not found in configuration file");
			return null;
		}
		
		Y3 instance = null;
		try {
			instance = (Y3) Class.forName(implementationClass).newInstance() ;
		} catch ( Throwable th ) {
			logger.fatal("Error instanciating client class '"+implementationClass+"'",th);
		}

		try {
			if ( instance != null && !(instance instanceof Y3Client) ) {
				logger.fatal("Client must extends Y3Client");
				instance = null;
			} else {
				((Y3Client) instance).initialize(properties);
			}
		} catch (Exception ex) {
			logger.fatal("Error initializing client",ex);
		}
		
		return instance;
	}
	
	/**
	 * Load the configuration file to determine the implementation
	 * to be used.
	 */
	private static void initializeFactory() {
		InputStream is = null ;
		try {
			is = Thread.currentThread().getContextClassLoader().getResourceAsStream(PROPERTIES_FILE_NAME);
		} catch ( Throwable th ) {
			is = null ;
			logger.fatal(PROPERTIES_FILE_NAME+" not found in librairies");
		} 
		
	    if ( is != null ) {
	    	try {
	    		properties = new Properties();
	    		properties.loadFromXML(is);
	    		initializationDone = true;
	    	} catch (Exception ex) {
	    		logger.fatal("Error occured parsing configuration file", ex);
	    	}
	    }
	}
	
}
